package com.chy.ruoyi.vue.codegen;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chy.ruoyi.vue.codegen.common.constant.GenConstants;
import com.chy.ruoyi.vue.codegen.common.utils.StringUtils;
import com.chy.ruoyi.vue.codegen.config.GenConfig;
import com.chy.ruoyi.vue.codegen.core.text.Convert;
import com.chy.ruoyi.vue.codegen.domain.GenTable;
import com.chy.ruoyi.vue.codegen.domain.GenTableColumn;
import com.chy.ruoyi.vue.codegen.service.GenTableColumnServiceImpl;
import com.chy.ruoyi.vue.codegen.service.GenTableServiceImpl;
import com.chy.ruoyi.vue.codegen.util.SpringUtil;
import org.apache.commons.io.IOUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;

@SpringBootApplication
@MapperScan("com.chy.ruoyi.vue.codegen.mapper")
public class CodeGenMain {
    public static void main(String[] args) {
        SpringApplication.run(CodeGenMain.class, args);
        System.out.println("hello");
        ApplicationContext applicationContext = SpringUtil.getApplicationContext();
        GenTableServiceImpl genTableService=applicationContext.getBean(GenTableServiceImpl.class);



        Scanner scan = new Scanner(System.in);
        System.out.println("请输入要生成的表名");
        String tableName=scan.next();
        while (true){
            if(tableName.equals("stop")){ //退出循环
                System.out.println("退出循环");
                break;
            }
            else {
                //查询表是否存在，并且是否已经导入
                //不存在继续输入
                if(IsExist(genTableService,tableName)) { //存在且未生成的表
                    IsImportTable(genTableService,tableName);//导入表结构
                    String tpl_category=GenConfig.getTpl_category();
                    if(GenConstants.TPL_SUB.equals(tpl_category)){ //如果是主子表，则还需要导入子表
                        String sub_table_name=GenConfig.getSub_table_name();//子表表名称
                        if(sub_table_name.equals("")){
                            System.out.println("你还没有配置好子表数据，请先配置子表。");
                            System.exit(0);//退出系统
                        }
                        else{
                            IsImportTable(genTableService,sub_table_name);//导入表结构
                        }
                    }

                    //生成代码
                    newGenrate(genTableService,tableName);
                    System.out.println("是继续生成还是退出？退出输入y");
                    tableName=scan.next();
                    if(tableName.equals("y")){
                        System.exit(0);
                    }
                }
                else {
                    //查询已经生成过的表，有则继续生成，没有再输入
                    if(!IsgenTable(genTableService, tableName)){
                        //不存在则继续输入表
                        System.out.println("请输入要生成的表名，输入Y则退出！");
                        tableName=scan.next();
                        if(tableName.equals("y")){
                            System.exit(0);
                        }
                    }
                    else{
                        //存在则生成代码
                        newGenrate(genTableService,tableName);
                        System.out.println("是继续生成还是退出？退出输入y");
                        tableName=scan.next();
                        if(tableName.equals("y")){
                            System.exit(0);
                        }
                    }

                }
            }
        }
        scan.close();
        System.exit(0);
    }

    //查询表是否存在数据库且是未导入到生成表的表
    public  static  boolean IsExist( GenTableServiceImpl genTableService,String tableName){

        GenTable genTable=new GenTable();
        genTable.setTableName(tableName);
        List<GenTable> list = genTableService.selectDbTableList(genTable);
        if(list==null||list.size()==0){
            System.out.println(tableName+"可能不存在数据库，也可能已经导入完成");
            return  false ;
        }
        else {
            return  true;
        }
    }

    public  static  boolean IsgenTable(GenTableServiceImpl genTableService,String tableName){
        GenTable table = genTableService.selectGenTableByName(tableName);
        if(table==null||table.getColumns().size()==0){
           return  false;
        }else {
            return  true;
        }
    }
    //查询是否已经导入,没有导入则导入，已经导入了，则跳过。 //导入信息
    public static  void IsImportTable(GenTableServiceImpl genTableService,String tableName){

        GenTable table = genTableService.selectGenTableByName(tableName);
         //不存在才需要导入，否则跳过
        if(table==null||table.getColumns().size()==0){
            String[] tableNames = Convert.toStrArray(tableName);
            // 查询表信息
            List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
            genTableService.importGenTable(tableList);
        }
    }

    //生成代码
    public  static  void  newGenrate(GenTableServiceImpl genTableService,String tableName){
        //模板类型
        String tpl_category=GenConfig.getTpl_category();
        GenTable table = genTableService.selectGenTableByName(tableName);
        Map<String, Object> map=new HashMap<String, Object>();
        if (GenConstants.TPL_TREE.equals(tpl_category)){

            map.put("treeCode", GenConfig.getTreeCode());
            map.put("treeName", GenConfig.getTreeName());
            map.put("treeParentCode", GenConfig.getTreeParentCode());
            map.put("parentMenuId", GenConfig.getParentMenuId());
            table.setParams(map);

            String options = StringUtils.format("{\"treeCode\":\"{}\",\"treeName\":\"{}\",\"treeParentCode\":\"{}\",\"parentMenuId\":\"{}\"}", GenConfig.getTreeCode(), GenConfig.getTreeName(),GenConfig.getTreeParentCode(),GenConfig.getParentMenuId());
            table.setOptions(options);
            //genTableService.updateGenTable(table); //设置树形模板东西
        }
        else if (GenConstants.TPL_SUB.equals(tpl_category)){
            map.put("treeCode", null);
            map.put("treeName", null);
            map.put("treeParentCode",null);
            map.put("parentMenuId", GenConfig.getParentMenuId());
            table.setParams(map);
            //子表表名称
            String sub_table_name=GenConfig.getSub_table_name();
            //设置名称
            table.setSubTableName(sub_table_name);
            //主表外键名称
            String sub_table_fk_name=GenConfig.getSub_table_fk_name();
            table.setSubTableFkName(sub_table_fk_name);


        }
        else { //普通表
            map.put("treeCode", null);
            map.put("treeName", null);
            map.put("treeParentCode",null);
            map.put("parentMenuId", GenConfig.getParentMenuId());
            table.setParams(map);
        }
        table.setTplCategory(tpl_category);
        //设置树形模板东西
        genTableService.updateGenTable(table);

        String[] tableNames = Convert.toStrArray(tableName);
        //第三步：生成压缩文件
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(tableName+".zip", data);
        System.out.println(tableName+"=====生成完了");
    }


    public static void generate(GenTableServiceImpl genTableService) {
        //第一步：检查是否存在历史数据并删除
        String tableName = "admin";
        GenTable req=new GenTable();
        req.setTableName(tableName);
        List<GenTable> genTables = genTableService.selectGenTableList(req);
        if (!CollectionUtils.isEmpty(genTables)) {
            // log.warn("表{}生成数据已存在，即将删除历史数据", tableName);
            Long[] array = new Long[genTables.size()];
            genTables.stream().map(GenTable::getTableId).collect(Collectors.toList()).toArray(array);
            genTableService.deleteGenTableByIds(array);
        }
        //第二步：导入表结构
        String[] tableNames = Convert.toStrArray(tableName);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);

        //第三步：生成压缩文件
        byte[] data = genTableService.downloadCode(tableNames);
        genCode("chy.zip", data);
        System.out.println("生成完了");
    }
    public static void genCode(String fileName, byte[] data) {
        try {

            FileOutputStream fos =new FileOutputStream(new File(fileName));
            IOUtils.write(data, fos);
            fos.close();
        } catch (IOException e) {
            // log.error("", e);
            System.out.println("ex"+e);
        }
    }
}
